import CryptoJS from 'crypto-js';
import hdyConfig from "@/config/index";
import {
	pathToBase64,
	base64ToPatch
} from 'image-tools'
// import api from '@/api/home/index.js';
//md5加密
let md5 = (data) => {
	return CryptoJS.MD5(data).toString()
}
let getFomartPrice = (str, fix = 1) => {
	if (!str) {
		return 0
	}
	let number = Number(str)
	if (number >= 10000 && number < 100000000) {
		number = number > 10000 ? (number / 10000).toFixed(fix) + '万' : number
	}
	if (number >= 100000000) {
		number = number > 100000000 ? (number / 100000000).toFixed(fix) + '亿' : number
	}
	return number
}
//防抖函数
let debounce = (func, wait) => {
	let timer = null;
	// func()
	return () => {
		clearTimeout(timer)
		timer = setTimeout(func(), wait)
	}
}
//导入到通讯录
function mobileCommunication(arr, isDecrypt) {
	console.log(arr)
	if (!arr || !arr.length) {
		uni.$u.toast('暂无信息可以导入')
		return false
	}
	uni.showLoading({
		title: '正在导出'
	});
	for (var i = 0; i < arr.length; i++) {
		const item = arr[i]
		const index = i
		uni.addPhoneContact({
			firstName: item.companyName,
			mobilePhoneNumber: isDecrypt ? item.phoneNumber : decrypt(item.phoneNumber),
			success: () => {
				// console.log('success');
				// console.log('index', index)
				if (index + 1 == arr.length) {
					uni.hideLoading();
					uni.$u.toast('导出成功')
				}

			},
			fail: function() {
				console.log('fail');
				checkPermission()

			}
		});
	}
}

function base64ToFile(base64, name) {
	if (typeof base64 !== 'string') {
		return
	}
	let arr = base64.split(',');

	let type = 'image/png';
	console.log(arr, type)
	let fieExt = 'png';
	let str = atob(arr[1])
	let i = str.length;
	let u8Array = new Uint8Array(i)
	while (i--) {
		u8Array[i] = str.charCodeAt(i)
	}
	console.log(new File([u8Array], `${name}.${fieExt}`, {
		type: type
	}))
	return new File([u8Array], `${name}.${fieExt}`, {
		type: type
	})

}

function imageToCanvas(file, canvasId, func, funcB) {
	let width = 0;
	let height = 0;
	uni.getImageInfo({
		src: file.path,
		success: (img) => {

		},
		fail: (res) => {
			console.log('获取图片失败=>', res)
		},
		complete: (img) => {
			console.log('获取图片完成=>', img)
			width = img.width;
			height = img.height;
			func({
				width,
				height
			})
			console.log(width, height)
			let ctx = uni.createCanvasContext(canvasId)
			ctx.drawImage(img.path, 0, 0, width, height);
			ctx.draw();
			uni.canvasToTempFilePath({
				x: 0,
				y: 0,
				canvasId: canvasId,
				success: (res) => {
					console.log('success=>', res)
				},
				fail: (res) => {

					console.log('fail =>', res)
				},
				complete: (res) => {
					funcB(res)
					console.log('complete=>', res)
				}
			})
		}
	})
}

//发送短信模版
function sendSMS(phoneNumber, message) {
	var msg = plus.messaging.createMessage(plus.messaging.TYPE_SMS);
	msg.to = phoneNumber
	msg.body = message
	plus.messaging.sendMessage(msg, (res) => {
		console.log(res)
	}, (error) => {
		console.log(error)
	})
}

function getPicStr(arr) {
	return arr.map(e => e.pict)?.join()
}

function guid(len = 32, firstU = true, radix = null) {
	let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	let uuid = [];
	radix = radix || chars.length;

	if (len) {
		// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
		for (let i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
	} else {
		let r;
		// rfc4122标准要求返回的uuid中,某些位为固定的字符
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';

		for (let i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | (Math.random() * 16);
				uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
			}
		}
	}
	// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
	if (firstU) {
		uuid.shift();
		return 'u' + uuid.join('');
	} else {
		return uuid.join('');
	}
}

function isToday(timestamp) {
	const now = new Date();
	const date = new Date(timestamp);

	return now.getUTCDate() === date.getUTCDate();
}


async function uploadToQiniu(file, callback, progress) {

	const suffix = file.split(".")[1];

	uni.request({
		url: hdyConfig.baseURL + '/pub/v1/qiniuUploadToken',
		method: 'get',
		header: {
			token: uni.getStorageSync('token')
		},
		success: res => {
			let {
				data
			} = res
			let uploadTask = uni.uploadFile({
				filePath: file,
				url: 'https://upload-z2.qiniup.com/',
				name: 'file',
				formData: {
					...data.data,
				},
				success: (res) => {
					let url = 'https://img.huirongke.com/' +
						data.data.key;
					callback(url)
				},
				complete: (res) => {
					if (res.statusCode == '400') {
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
						callback({
							status: 'error'
						})
						return
					}
				},
				error: (res) => {}
			})
			uploadTask.onProgressUpdate((res) => {
				progress(res)
			})
		},
		error: (res) => {
			uni.showToast({
				title: '请求出错',
				icon: 'none'
			})
		}
	})



}

function checkPermission(error) {
	console.log(error)
	uni.showModal({
		title: '提示',
		content: '您拒绝了权限申请，请前往设置开启相关权限',
		complete: (res) => {
			if (res.confirm) {
				let key = "android.settings.APPLICATION_SETTINGS"
				console.log(key)
				let main = plus.android.runtimeMainActivity()
				let Intent = plus.android.importClass('android.content.Intent');
				let mIntent = new Intent(key);
				main.startActivity(mIntent)
			}
		}
	})

}
export {
	md5,
	getFomartPrice,
	debounce,
	mobileCommunication,
	sendSMS,
	getPicStr,
	imageToCanvas,
	base64ToFile,
	guid,
	isToday,
	uploadToQiniu,
	checkPermission
}